package com.spzx.order.service.impl;

import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-06-26
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderItemMapper orderItemMapper;


    @Override
    public TradeVo orderTradeData() {
        TradeVo tradeVo = new TradeVo();
        //生成订单号
        String tradeNo = generateTradeNo();
        //tradeVo设置订单号
        tradeVo.setTradeNo(tradeNo);

        //购物车选中商品
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (R.FAIL == cartCheckedListResult.getCode()) {
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        List<CartInfo> cartInfoList = cartCheckedListResult.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车中没有选中的商品");
        }
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfoList) {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            orderItemList.add(orderItem);
        }
        tradeVo.setOrderItemList(orderItemList);

        //购物车商品总金额
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (OrderItem orderItem : orderItemList) {
            BigDecimal price = orderItem.getSkuPrice()
                    .multiply(new BigDecimal(orderItem.getSkuNum()));
            totalPrice = totalPrice.add(price); // 关键：接收 add() 返回的新对象
        }
        tradeVo.setTotalAmount(totalPrice);

        //是否是立即购买
        tradeVo.setIsBuy(false);


        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        //获取用户id
        Long userId = SecurityUtils.getUserId();

        //1 防止订单重复提交&防止页面停留超时
        // TODO

        //2 判断价格是否改变并更新购物车中的商品价格
        // 2.1 批量获取商品实时价格 TODO
        // 2.2 并判断价格是否变更 TODO
        // 2.3 如果有变更，则更新购物车中的商品价格 TODO


        //3 校验库存并锁定库存
        // TODO

        //4 下单
        Long orderId = saveOrder(orderForm);


        //5 删除购物车选中商品
        if(!orderForm.getIsBuy()){
            R<Boolean> deleteResult = remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);
            if (R.FAIL == deleteResult.getCode()) {
                log.error(deleteResult.getMsg());
                //非核心流程不影响程序的执行
                //throw new ServiceException(deleteResult.getMsg());
            }
        }

        return orderId;
    }

    private Long saveOrder(OrderForm orderForm) {

        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        // 保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderForm.getTradeNo());//订单号
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //订单状态
        orderInfo.setOrderStatus(0);//待付款
        orderInfo.setCreateBy(userName);
        orderInfo.setUpdateBy(userName);

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItemList
                .stream()
                .map(
                        orderItem -> orderItem
                                .getSkuPrice()
                                .multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //设置商品总价格
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);//原价
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券价格

        //远程调用获取用户地址信息
        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if(R.FAIL == userAddressResult.getCode()){
            throw new ServiceException(userAddressResult.getMsg());
        }
        //获取用户地址信息
        UserAddress userAddress = userAddressResult.getData();
        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        orderInfo.setRemark(userAddress.getRemark());

        baseMapper.insert(orderInfo);
        // 保存订单项记录：order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateBy(userName);
            orderItem.setUpdateBy(userName);
            orderItemMapper.insert(orderItem);
        }

        return orderInfo.getId();

    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo() {
        Long userId = SecurityUtils.getUserId();
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }
}